layui.use(['layer', 'form', 'table', 'util', 'admin', 'element', 'laydate', 'jquery', 'dropdown', 'treeTable', 'xmSelect'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var admin = layui.admin;
    var element = layui.element;
    var laydate = layui.laydate;
    var xmSelect = layui.xmSelect;
    var treeTable = layui.treeTable;

    //渲染日期组件，如果存在的话
    renderLayDateCp($, laydate);


    //渲染表格
    var menuInsTb = treeTable.render({
        id: "menuTable",
        elem: '#menuTable',
        url: prefix + '/list',
        page: true,
        height: 'full-150',
        method: 'post',
        toolbar: ['<p>',
            '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn ' + addFlag + '"><i class="layui-icon layui-icon-addition"></i>添加</button>&nbsp;',
            '<button lay-event="expandAll" class="layui-btn layui-btn-sm layui-bg-cyan icon-btn"><i class="layui-icon layui-icon-addition"></i>展开全部</button>&nbsp;',
            '<button lay-event="foldAll" class="layui-btn layui-btn-sm layui-bg-cyan icon-btn"><i class="layui-icon layui-icon-subtraction"></i>折叠全部</button>&nbsp;',
            '</p>'].join(''),
        initSort: {
            field: 'orderNum'
            , type: 'asc'
        },
        where: {
            fieldName: 'orderNum'
            , sortType: 'asc'
        },
        tree: {
            iconIndex: 2,
            idName: 'menuId',
            pidName: 'parentId',
            isPidData: true
        },
        cols: [
            [
                {type: 'radio'},
                {type: 'numbers'},
                {field: 'menuName', title: '菜单名称', minWidth: 200},
                {field: 'orderNum', title: '排序', width: 100},
                {
                    field: 'icon', title: '图标', width: 100, templet: function (d) {
                        return '<i class="' + d.icon + '"></i>';
                    }
                },
                {field: 'url', title: '请求地址'},
                {
                    field: 'menuType', title: '菜单类型', templet: function (d) {
                        return showDictLabel(dictSysMenuType, d.menuType);
                    }, sort: true, width: 120
                },
                {
                    field: 'perms', title: '权限标识', templet: function (d) {
                        return d.perms && d.perms !== "" ? d.perms : "-";
                    }
                },
                {
                    field: 'visible', title: '菜单状态', templet: function (d) {
                        return showDictLabel(dictSysShowHide, d.visible);
                    }, sort: true, width: 120
                },
                {title: '操作', toolbar: '#menuTbBar', align: 'center', minWidth: 200}
            ]
        ]
    });


//表格搜索
    form.on('submit(menuTbSearch)', function (data) {
        menuInsTb.reload({where: data.field, page: {curr: 1}});
        return false;
    });


//表头工具栏点击事件
    treeTable.on('toolbar(menuTable)', function (obj) {
        if (obj.event === "add") {
            showEditModel();
        } else if (obj.event === "expandAll") {
            menuInsTb.expandAll();  // 展开全部
        } else if (obj.event === "foldAll") {
            menuInsTb.foldAll();  // 折叠全部
        }
    });


//表格工具条点击事件
    treeTable.on('tool(menuTable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            deleteData(data.menuId);
        } else if (obj.event === 'edit') {
            showEditModel(data);
        } else if (obj.event === "add") {
            showEditModel({parentId: data.menuId, url: data.url}, true);
        }
    });

    form.on('radio(menuType)', function (data) {
        var type = data.value;
        dynamicForm(type);
    });


//编辑或添加
    function showEditModel(mData, isAddSonMenu) {
        if (isAddSonMenu === undefined) {
            isAddSonMenu = false;
        }
        admin.open({
            type: 1,
            area: '550px',
            title: (mData ? '添加' : '修改') + '菜单权限表',
            content: $('#menuEditDialog').html(),
            success: function (layero, dIndex) {
                form.render();
                if (mData) {
                    // 回显表单数据
                    form.val('menuEditForm', mData);
                    dynamicForm(mData.menuType)
                } else {
                    dynamicForm('C');
                }
                // 表单提交事件
                form.on('submit(menuEditSubmit)', function (data) {
                    var loadIndex = layer.load(2);
                    admin.req(prefix + (mData && !isAddSonMenu ? '/edit' : '/add'), data.field, function (resp) {
                        layer.close(loadIndex);
                        if (resp.code === 0) {
                            layer.close(dIndex);
                            himio.notice.success(resp.msg);
                            menuInsTb.reload({page: {curr: 1}});
                        } else {
                            himio.notice.error(resp.msg);
                        }
                    }, 'post');
                    return false;
                });
                //渲染菜单树
                var td = [{name: "主目录", value: 0, selected: true, children: allMenuTree}];
                var parentMenuSel = xmSelect.render({
                    el: '#gen-menu-tree',
                    tips: '主目录',
                    radio: true,
                    clickClose: true,
                    name: 'parentId',
                    layVerify: 'required',
                    layVerType: 'tips',
                    filterable: true,
                    tree: {
                        show: true,
                        strict: false,
                        expandedKeys: [0]
                    },
                    height: 350,
                    data: td
                });
                if (mData) {
                    parentMenuSel.update({disabled: mData.parentId === 0});
                    parentMenuSel.setValue([mData.parentId]);
                }

                //渲染菜单 url 下拉（把所有的工程已有的 url 展示出来方便勾选，没有的可以自行编辑创建）
                var urlListMap = []
                for (var i = 0; i < urlSet.length; i++) {
                    urlListMap.push({
                        name: urlSet[i],
                        value: urlSet[i]
                    });
                }
                var menuUrlSel = xmSelect.render({
                    el: '#menuUrl',
                    name: 'url',
                    layVerType: 'tips',
                    radio: true,
                    clickClose: true,
                    filterable: true,
                    create: function (val, arr) {
                        if (urlSet.indexOf(val) === -1) {
                            return {
                                name: val,
                                value: val
                            }
                        }
                    },
                    model: {
                        icon: 'hidden',
                        label: {
                            type: 'text'
                        }
                    },
                    data: urlListMap
                })
                if (mData && !isAddSonMenu) {
                    if (urlSet.indexOf(mData.url) === -1) {
                        urlListMap.push({name: mData.url, value: mData.url});
                        menuUrlSel.update({data: urlListMap});
                    }
                }
                menuUrlSel.setValue(mData ? [mData.url] : []);

                // 禁止弹窗出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

//删除
    function deleteData(data) {
        if (data.length === 0) {
            himio.notice.warn('请选择要删除的数据');
            return;
        }
        admin.confirm("确认要删除吗?", function (index) {
            layer.close(index);
            var loadIndex = layer.load(2);
            admin.req(prefix + "/remove/" + data, function (resp) {
                layer.close(loadIndex);
                himio.notice.resp(resp, function () {
                    menuInsTb.reload({where: data.field, page: {curr: 1}});
                });
                layer.close(index);
            }, "post");
        });
    }

});


function selectIcon() {
    layer.open({
        type: 2,
        title: "字体图标列表",
        area: ['480px', '500px'],
        fixed: false, //不固定
        content: prefix + '/font/list'
    });
}

function dynamicForm(type) {
    $("#menuEditForm>.layui-hide").removeClass("layui-hide");
    if (type === 'M') {
        $("input[name=url]").parents(".layui-form-item").addClass("layui-hide");
        $("input[name=perms]").parents(".layui-form-item").addClass("layui-hide");
        $("select[name=target]").parents(".layui-form-item").addClass("layui-hide");
    } else if (type === 'F') {
        $("input[name=url]").parents(".layui-form-item").addClass("layui-hide");
        $("input[name=visible]").parents(".layui-form-item").addClass("layui-hide");
        $("input[name=icon]").parents(".layui-form-item").addClass("layui-hide");
        $("select[name=target]").parents(".layui-form-item").addClass("layui-hide");
    }
}